package com.leantech.android.browser.ui

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.cscj.android.utils.LOG
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch

class InterstitialAdViewModel : ViewModel() {


    /**
     * 统计浏览器加载URL次数，每5个展示插屏
     */
    private val urlLoadCountFlow = MutableStateFlow(0)

    /**
     * 当前广告状态，只有在Idle时允许新的广告请求
     */
    private val adStateFlow = MutableStateFlow<InterstitialAdState>(InterstitialAdState.Idle)

    private val adRequestCount = MutableStateFlow(0)

    /**
     * 广告加载Flow
     * 如果是Accept表示需要加载广告
     * 只有在广告状态时Idle时才会有效
     */
    val adLoadFlow: Flow<InterstitialAdLoadSignal> =
        combine(urlLoadCountFlow, adStateFlow, adRequestCount) { loadCount, adState, requestCount ->
            LOG.d("InterstitialAd", "state change loadCount $loadCount , adState $adState , requestCount $requestCount")
            (loadCount > 0 && loadCount % 5 == 0 || requestCount > 0) && adState == InterstitialAdState.Idle
        }.flatMapLatest { willLoadAd ->
            if (willLoadAd) {
                flowOf(InterstitialAdLoadSignal.Accept)
            } else {
                flowOf(InterstitialAdLoadSignal.Denied)
            }
        }

    /**
     * 每次加载完url时，调用
     */
    fun increaseLoadCount() {
        urlLoadCountFlow.update {
            it + 1
        }
    }

    fun requestLoadAd(resetUrlCount: Boolean = true) {
        adRequestCount.update {
            it + 1
        }
        if (resetUrlCount) {
            viewModelScope.launch {
                urlLoadCountFlow.emit(0)
            }
        }
    }

    /**
     * 广告关闭后调用
     */
    fun onAdClose() {
        viewModelScope.launch {
            adRequestCount.emit(0)
            urlLoadCountFlow.emit(0)
            adStateFlow.emit(InterstitialAdState.Idle)
        }
    }

    fun markAdStateLoading() {
        viewModelScope.launch {
            adStateFlow.emit(InterstitialAdState.Loading)
        }
    }

    fun markAdStateShow() {
        viewModelScope.launch {
            adStateFlow.emit(InterstitialAdState.Show)
        }
    }


    /**
     * 插屏广告状态
     */
    sealed interface InterstitialAdState {
        data object Idle : InterstitialAdState

        data object Loading : InterstitialAdState

        data object Show : InterstitialAdState

    }

    sealed interface InterstitialAdLoadSignal {
        data object Accept : InterstitialAdLoadSignal

        data object Denied : InterstitialAdLoadSignal
    }

}